//
//  GuestCommunitySelectViewController.m
//  QRMaster
//
//  Created by myApple on 15/6/10.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "GuestCommunitySelectViewController.h"
#import "RequestNetWork.h"
#import "BulidingModel.h"
#import "GuestCommunityChangeCell.h"
#import "OpertionPlist.h"
#import "communityModel.h"
#import "DropDownMenuView.h"
#import "AppDelegate.h"
#import "PromptInfoView.h"
#import "StartPageController.h"
#import "checkPower.h"
#import "GetNameByID.h"
#import "BulidingInfoLogic.h"
#import "FloorsInfoLogic.h"
#import "RoomInfoLogic.h"
#import "RoomsModel.h"
#import "userInfoModel.h"
#import "BackBtn.h"
#import "CommunityListInfo.h"

@interface GuestCommunitySelectViewController ()<UITableViewDataSource,UITableViewDelegate,DropDownMenuViewDelegate>
{
    UITableView * leftTableView;
    UITableView * middleTableView;
    UITableView * rightTableView;
    
    NSString * communityid;
    NSString * bulidingid;
    NSString * floorid;
    NSString * roomid;
    
    NSMutableArray * bulidingArray;
    NSMutableArray * floorArray;
    NSMutableArray * roomArray;
    
    
    NSMutableArray * CommunityInfoArray;
    UIButton * communityNameBtn;
    
    //下拉列表选择框
    DropDownMenuView * CommunityDDView;
    BOOL communityNameFlag;
    UIControl * backViewControl;
    
    AppDelegate * appDelegate;
    
    BulidingModel * allBuliding;
    FloorsModel * allFloor;
    RoomsModel * allRoom;
    
    UIView  * titleView;
    
    UIActivityIndicatorView * _activityIndicator;
}

@end

@implementation GuestCommunitySelectViewController

-(id)initWith:(NSString *)_communityid withBulidingId:(NSString *)_bulidingId withFloorId:(NSString *)_floorId withRoomId:(NSString *)_roomId
{
    self = [super init];
    if (self) {
        allBuliding = [[BulidingModel alloc]init];
        allFloor = [[FloorsModel alloc]init];
        allRoom = [[RoomsModel alloc]init];
        allBuliding.buildingName=NSLocalizedString(@"allBuliding", nil);
        allFloor.floorName=NSLocalizedString(@"allFloor", nil);
        allRoom.roomName=NSLocalizedString(@"allRoom", nil);
        
        bulidingArray = [[NSMutableArray alloc]init];
        floorArray = [[NSMutableArray alloc]init];
        roomArray = [[NSMutableArray alloc]init];
        appDelegate = [UIApplication sharedApplication].delegate;
        communityNameFlag = NO;
        communityid = _communityid;
        CommunityInfoArray = [[NSMutableArray alloc]init];
        bulidingid = _bulidingId;
        floorid = _floorId;
        roomid = _roomId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
//    [self prepareTitleView];
    [self prepareTabelView];
//    [self prepareDropDownView];
    self.title = NSLocalizedString(@"changeroom", nil);
    [self getDataFromContentFile];
    [self prepareActivityIndicator];
   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    titleView.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [CommunityDDView showOrNotList:YES];
    titleView.hidden = YES;
}

-(void)initData
{
    BulidingInfoLogic *bulidingInfoLogic = [[BulidingInfoLogic alloc]init];
    
    [bulidingInfoLogic queryBulidingInfo:communityid block:^(NSMutableArray *mybulidingArray)
     {
         bulidingArray = mybulidingArray;
     }];
    
    if (bulidingid == nil || [@"" isEqualToString:bulidingid] == YES) {
        if (bulidingArray.count>0) {
            bulidingid = ((BulidingModel *)[bulidingArray objectAtIndex:0]).buildingId;
        }
    }
    
    if (bulidingArray.count>0) {
        [bulidingArray insertObject:allBuliding atIndex:0];
    }
    
    FloorsInfoLogic *floorInfoLogic = [[FloorsInfoLogic alloc]init];
    [floorInfoLogic queryFloorsInfo:bulidingid block:^(NSMutableArray *arr)
     {
         floorArray = arr;
     }];
    
    if (floorid == nil || [@"" isEqualToString:floorid] == YES) {
        if (floorArray.count>0) {
            floorid = ((FloorsModel *)[floorArray objectAtIndex:0]).floorId;
        }
    }
    if (floorArray.count>0) {
        [floorArray insertObject:allFloor atIndex:0];
    }
    
    RoomInfoLogic *roomInfoLogic = [[RoomInfoLogic alloc]init];
    [roomInfoLogic queryRoomInfo:floorid block:^(NSMutableArray *myRoomArray)
     {
         roomArray = myRoomArray;
     }
     ];
    
    if (roomid == nil || [@"" isEqualToString:roomid] == YES) {
        if (roomArray.count>0) {
            roomid = ((RoomsModel *)[roomArray objectAtIndex:0]).roomId;
        }
    }
    if (roomArray.count>0) {
        [roomArray insertObject:allRoom atIndex:0];
    }
    
    [leftTableView reloadData];
    [middleTableView reloadData];
    [rightTableView reloadData];
    
    [self getHouseData];


}

//-(void)setCommunityId:(NSString *)communityId
//{
//    _communityId = communityId;
//    communityid = communityId;
//    CommunityInfoArray = [[NSMutableArray alloc]init];
//
//}
//
//
//-(void)setBulidingId:(NSString *)bulidingId
//{
//    _bulidingId = bulidingId;
//    bulidingid = bulidingId;
//    
//    BulidingInfoLogic *bulidingInfoLogic = [[BulidingInfoLogic alloc]init];
//
//    [bulidingInfoLogic queryBulidingInfo:communityid block:^(NSMutableArray *mybulidingArray)
//    {
//        bulidingArray =mybulidingArray;
//    }];
//    
//    if (bulidingid == nil || [@"" isEqualToString:bulidingid] == YES) {
//        if (bulidingArray.count>0) {
//            bulidingid = ((BulidingModel *)[bulidingArray objectAtIndex:0]).buildingId;
//        }
//    }
//
//    if (bulidingArray.count>0) {
//        [bulidingArray insertObject:allBuliding atIndex:0];
//    }
//}
//
//-(void)setFloorId:(NSString *)floorId
//{
//    _floorId = floorId;
//    floorid = floorId;
//    
//    FloorsInfoLogic *floorInfoLogic = [[FloorsInfoLogic alloc]init];
//    [floorInfoLogic queryFloorsInfo:bulidingid block:^(NSMutableArray *arr)
//    {
//        floorArray = arr;
//    }];
//    
//    if (floorid == nil || [@"" isEqualToString:floorid] == YES) {
//        if (floorArray.count>0) {
//            floorid = ((FloorsModel *)[floorArray objectAtIndex:0]).floorId;
//        }
//    }
//    if (floorArray.count>0) {
//        [floorArray insertObject:allFloor atIndex:0];
//    }
//
//}
//
//-(void)setRoomId:(NSString *)roomId
//{
//    _roomId = roomId;
//    roomid = roomId;
//    
//    RoomInfoLogic *roomInfoLogic = [[RoomInfoLogic alloc]init];
//    [roomInfoLogic queryRoomInfo:floorid block:^(NSMutableArray *myRoomArray)
//    {
//        roomArray = myRoomArray;
//    }
//    ];
//    
//    if (roomid == nil || [@"" isEqualToString:roomid] == YES) {
//        if (roomArray.count>0) {
//            roomid = ((RoomsModel *)[roomArray objectAtIndex:0]).roomId;
//        }
//    }
//    if (roomArray.count>0) {
//        [roomArray insertObject:allRoom atIndex:0];
//    }
//    
//    [leftTableView reloadData];
//    [middleTableView reloadData];
//    [rightTableView reloadData];
//
//    [self getHouseData];
//}


#pragma mark -- 根据传过来的id号来请求房间数据
-(void)getHouseData
{
//    [self startWaiting:nil color:nil addToView:self.view];
    _activityIndicator.hidden = NO;
    [_activityIndicator startAnimating];
    __block GetNameByID * getName = [GetNameByID shareGetNameByID];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:communityid forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(ALLHOTELINFO) params:postDict block:^(id downLoadData, id error)
     {
//         [self stopWaiting];
         [_activityIndicator stopAnimating];
         _activityIndicator.hidden = YES;
         if ([downLoadData objectForKey:@"data"] != nil) {
             [bulidingArray removeAllObjects];
             [floorArray removeAllObjects];
             [roomArray removeAllObjects];
             for (NSMutableDictionary *dic in [downLoadData objectForKey:@"data"])
             {
                 BulidingModel *bulidModel = [[BulidingModel alloc]init];
                 bulidModel.buildingId=[dic objectForKey:@"buildingid"];
                 bulidModel.buildingName=[dic objectForKey:@"buildingname"];
                 bulidModel.buildingNo=[dic objectForKey:@"buildingno"];
                 bulidModel.floors =[dic objectForKey:@"floors"];
                 [bulidingArray addObject:bulidModel];
             }
             [self deleteRooms];
             [self insertDataIntoRooms:[downLoadData objectForKey:@"data"]];
             getName.bulidingArray = [[downLoadData objectForKey:@"data"] mutableCopy];
             if (roomid == nil || [@"" isEqualToString:roomid] == YES)
             {
                 if (bulidingArray.count > 0) {
                     bulidingid = ((BulidingModel *)bulidingArray[0]).buildingId;
                     for (NSMutableDictionary  *dic in ((BulidingModel *)bulidingArray[0]).floors)
                     {
                         FloorsModel *myFloorsModel = [[FloorsModel alloc]init];
                         myFloorsModel.floorId = [dic objectForKey:@"floorid"];
                         myFloorsModel.floorName = [dic objectForKey:@"floorname"];
                         myFloorsModel.floorNo = [dic objectForKey:@"floorno"];
                         myFloorsModel.rooms = [dic objectForKey:@"rooms"];
                         [floorArray addObject:myFloorsModel];
                     }
                     if (floorArray.count > 0) {
                         floorid = ((FloorsModel *)floorArray[0]).floorId;
                         for (NSMutableDictionary *dic in ((FloorsModel *)[floorArray objectAtIndex:0]).rooms)
                         {
                             RoomsModel *myRoomsModel = [[RoomsModel alloc]init];
                             myRoomsModel.roomId=[dic objectForKey:@"roomid"];
                             myRoomsModel.roomName=[dic objectForKey:@"roomname"];
                             myRoomsModel.roomNo=[dic objectForKey:@"roomno"];
                             myRoomsModel.isSelect=[dic objectForKey:@"isselect"];
                             myRoomsModel.lockNo=[dic objectForKey:@"lockno"];
                             [roomArray addObject:myRoomsModel];
                         }
                         if (roomArray.count > 0)
                         {
                             roomid = ((RoomsModel *)roomArray[0]).roomId;
                         }
                     }
                 }
             }
             else
             {
                 for (BulidingModel * model in bulidingArray) {
                     if ([model.buildingId isEqualToString:bulidingid]) {
                         for (NSMutableDictionary  *dic in model.floors)
                         {
                             FloorsModel *myFloorsModel = [[FloorsModel alloc]init];
                             myFloorsModel.floorId = [dic objectForKey:@"floorid"];
                             myFloorsModel.floorName = [dic objectForKey:@"floorname"];
                             myFloorsModel.floorNo = [dic objectForKey:@"floorno"];
                             myFloorsModel.rooms = [dic objectForKey:@"rooms"];
                             [floorArray addObject:myFloorsModel];
                             
                         }
                         for (FloorsModel * myFloorsModel in floorArray) {
                             if ([myFloorsModel.floorId isEqualToString:floorid]) {
                                 for (NSMutableDictionary *dic  in myFloorsModel.rooms ) {
                                     RoomsModel *myRoomsModel = [[RoomsModel alloc]init];
                                    
                                     myRoomsModel.roomId=[dic objectForKey:@"roomid"];
                                     myRoomsModel.roomName=[dic objectForKey:@"roomname"];
                                     myRoomsModel.roomNo=[dic objectForKey:@"roomno"];
                                     myRoomsModel.isSelect=[dic objectForKey:@"isselect"];
                                     myRoomsModel.lockNo=[dic objectForKey:@"lockno"];
                                     [roomArray addObject:myRoomsModel];
                                 }
                             }
                             
                         }
                     }
                 }
             }
             [bulidingArray insertObject:allBuliding atIndex:0];
             [floorArray insertObject:allFloor atIndex:0];
             [roomArray insertObject:allRoom atIndex:0];
//             [self getDataFromDisk];
             [leftTableView reloadData];
             [middleTableView reloadData];
             [rightTableView reloadData];
         }
         else if (error != nil) {
             getName.bulidingArray = nil;
             [bulidingArray removeAllObjects];
             [floorArray removeAllObjects];
             [roomArray  removeAllObjects];
             [leftTableView reloadData];
             [middleTableView reloadData];
             [rightTableView reloadData];
             
//             [bulidingArray insertObject:allBuliding atIndex:0];
//             [floorArray insertObject:allFloor atIndex:0];
//             [roomArray insertObject:allRoom atIndex:0];

             if ([[error objectForKey:@"status"]integerValue] == 301) {
                 [self deleteRooms];
                 [PromptInfoView showMessage:NSLocalizedString(@"noRoomInfo", nil)];
             }
             else
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
             }
         }
         
     }
    ];
}

-(void)getDataFromDisk
{
    [bulidingArray removeAllObjects];
    [floorArray removeAllObjects];
    [roomArray removeAllObjects];
    BulidingInfoLogic *bulidingInfoLogic = [[BulidingInfoLogic alloc]init];
    [bulidingInfoLogic queryBulidingInfo:communityid block:^(NSMutableArray *mybulidingArray)
     {
         bulidingArray =mybulidingArray;
     }];
    
    if (bulidingid == nil || [@"" isEqualToString:bulidingid] == YES) {
        if (bulidingArray.count>0) {
            bulidingid = ((BulidingModel *)[bulidingArray objectAtIndex:0]).buildingId;
        }
    }
    
    if (bulidingArray.count>0) {
        [bulidingArray insertObject:allBuliding atIndex:0];
    }

    FloorsInfoLogic *floorInfoLogic = [[FloorsInfoLogic alloc]init];
    [floorInfoLogic queryFloorsInfo:bulidingid block:^(NSMutableArray *arr)
     {
         floorArray = arr;
     }];
    
    if (floorid == nil || [@"" isEqualToString:floorid] == YES) {
        if (floorArray.count>0) {
            floorid = ((FloorsModel *)[floorArray objectAtIndex:0]).floorId;
        }
    }
    if (floorArray.count>0) {
        [floorArray insertObject:allFloor atIndex:0];
    }

    RoomInfoLogic *roomInfoLogic = [[RoomInfoLogic alloc]init];
    [roomInfoLogic queryRoomInfo:floorid block:^(NSMutableArray *myRoomArray)
     {
         roomArray = myRoomArray;
     }
     ];
    
    if (roomid == nil || [@"" isEqualToString:roomid] == YES) {
        if (roomArray.count>0) {
            roomid = ((RoomsModel *)[roomArray objectAtIndex:0]).roomId;
        }
    }
    if (roomArray.count>0) {
        [roomArray insertObject:allRoom atIndex:0];
    }
}
-(void)getHouseNewData:(NSNotification *)not
{
    bulidingArray = [not.userInfo objectForKey:@"data"];
    //roomid 为空表示第一次进来
    if (roomid == nil) {
        if (bulidingArray.count > 0) {
            bulidingid = [bulidingArray[0]objectForKey:@"buildingid"];
             floorArray = [[bulidingArray[0]objectForKey:@"floors"] mutableCopy];
            if (floorArray.count > 0) {
                floorid = [floorArray[0]objectForKey:@"floorid"];
                 roomArray = [[floorArray[0]objectForKey:@"rooms"] mutableCopy];
                if (roomArray.count > 0) {
                    roomid = [roomArray[0]objectForKey:@"roomid"];
                }
            }
        }
    }
    else
    {
        for (NSDictionary * dict in bulidingArray) {
            if ([[dict objectForKey:@"buildingid"]isEqualToString:bulidingid]) {
                floorArray = [[dict objectForKey:@"floors"] mutableCopy];
                for (NSDictionary * fdict in floorArray) {
                    if ([[fdict objectForKey:@"floorid"]isEqualToString:floorid]) {
                        roomArray = [[fdict objectForKey:@"rooms"] mutableCopy];
                    }
                    
                }
            }
        }
    }
    [bulidingArray insertObject:allBuliding atIndex:0];
    [floorArray insertObject:allFloor atIndex:0];
    [roomArray insertObject:allRoom atIndex:0];
    [leftTableView reloadData];
    [middleTableView reloadData];
    [rightTableView reloadData];

}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = 44;
    
    titleView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    titleView.backgroundColor = [UIColor blackColor];
    titleView.userInteractionEnabled = YES;
    [self.navigationController.navigationBar addSubview:titleView];
    
    x = 10;
    y = 0;
    height = 40;
    width = 40;
    UIButton * backBtn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"24x24"];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:backBtn];
    
    //显示集群名称
    x = 50;
    y = 5;
    width = ScreenWidth - x - 70;
    height = 34;
    communityNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    communityNameBtn.frame = CGRectMake(x, y, width, height);
    [communityNameBtn setTitleColor:[UIColor whiteColor] forState:0];
    communityNameBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [communityNameBtn addTarget:self action:@selector(ChangeCommunity) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:communityNameBtn];
    
    x += width;
    width = 15;
    y = 14;
    height = 15;
    UIButton * communityChangeBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [communityChangeBtn setImage:[UIImage imageNamed:@"ic_triangle"] forState:0];
    [communityChangeBtn addTarget:self action:@selector(ChangeCommunity) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:communityChangeBtn];
    
    x = ScreenWidth - 40;
    width = 20;
    y = 12;
    height = 20;
    UIImageView * ImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    ImgView.image = [UIImage imageNamed:@"ic_refresh"];
    ImgView.userInteractionEnabled = YES;
    [titleView addSubview:ImgView];
    
    UITapGestureRecognizer * refreshCommunityTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refreshClick:)];
    [ImgView addGestureRecognizer:refreshCommunityTap];
    
}

-(void)getDataFromContentFile
{
    [CommunityInfoArray removeAllObjects];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    NSArray * communityData = [data objectForKey:COMMUNITYINFOFORKEY];
     CommunityListInfo * listInfo = [[CommunityListInfo alloc]init];
    for (NSDictionary * dict in communityData) {
        CommunityModel * model = [[CommunityModel alloc]init];
        model.communityName = [dict objectForKey:@"communityname"];
        model.communityId = [dict objectForKey:@"communityid"];
        model.role = [dict objectForKey:@"role"];
        model.areaCode = [dict objectForKey:@"areaCode"];
        [CommunityInfoArray addObject:model];
        [listInfo deleteCommunityListInfo:[dict objectForKey:@"communityid"]];
        [listInfo insertCommunityListInfo:[dict objectForKey:@"communityid"] withCommunityName:[dict objectForKey:@"communityname"]withCommunityAreaCode:[dict objectForKey:@"areaCode"]];
        if ([communityid isEqualToString:model.communityId]) {
            [communityNameBtn setTitle:model.communityName forState:0];
        }
    }
}

-(void)prepareDropDownView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 64;
    float width = ScreenWidth;
    float height = 0;
    
    //底部view让其下拉消失
    backViewControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, width, UI_SCREEN_HEIGHT)];
    backViewControl.alpha = 0.5;
    backViewControl.hidden = YES;
    [backViewControl addTarget:self action:@selector(removeDropDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backViewControl];
    
    CommunityDDView = [[DropDownMenuView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    CommunityDDView.delegate = self;
    CommunityDDView.hidden = YES;
    [backViewControl addSubview:CommunityDDView];
    
}

-(void)removeDropDown
{
    [CommunityDDView showOrNotList:YES];
    communityNameFlag = NO;
    backViewControl.hidden = YES;
}

-(void)ChangeCommunity
{
    if (communityNameFlag)
    {
        backViewControl.hidden = YES;
    }
    else
    {
        backViewControl.hidden = NO;
    }
    NSMutableArray * communityNameArray = [[NSMutableArray alloc]init];
    for (CommunityModel * model in CommunityInfoArray) {
        [communityNameArray addObject:model.communityName];
    }
    CommunityDDView.data = communityNameArray;
    [CommunityDDView showOrNotList:communityNameFlag];
    communityNameFlag =!communityNameFlag;
}

#pragma mark -- 获取集群信息
-(void)refreshClick:(UITapGestureRecognizer *)tap
{
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak GuestCommunitySelectViewController * guestSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        [guestSelf stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            [guestSelf getDataFromContentFile];
        }
        else if (error != nil) {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    };
}


#pragma mark --- DropDownMenuViewDelegate
-(void)DropDownMenuView:(DropDownMenuView *)menuView showIndex:(int)index back:(BOOL)flag
{
    if([self IsHaveNetwork] == YES)
    {
        return;
    }
    CommunityModel * model = CommunityInfoArray[index];
    //判读是否改变了集群，如果改变则要及时改变集群的楼栋信息
    if (![model.communityId isEqualToString:communityid]) {
        bulidingid = @"";
        floorid = @"";
        roomid = @"";
        communityid = model.communityId;
        [[NSUserDefaults standardUserDefaults] setObject:communityid forKey:@"communityId"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [QRSingleton sharedQRSingleton].communityId = model.communityId;
        [QRSingleton sharedQRSingleton].communityName = model.communityName;
        [QRSingleton sharedQRSingleton].currentAreaCodeString = model.areaCode;
        [self getHouseData];
    
    }
    [communityNameBtn setTitle:model.communityName forState:0];
    communityNameFlag = flag;
    backViewControl.hidden = YES;
}


#pragma mark -- 集群没有房子的处理
-(void)failRequest
{
    if (_HouseInfo) {
        self.HouseInfo(communityid,@"",@"",@"");
    }
    [bulidingArray removeAllObjects];
    [floorArray removeAllObjects];
    [roomArray removeAllObjects];
    [leftTableView reloadData];
    [rightTableView reloadData];
    [middleTableView reloadData];
}

-(void)prepareTabelView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth * 3 / 8.0;
    float height = ScreenHeight - y;
    
    leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height - 64) style:UITableViewStylePlain];
    leftTableView.delegate = self;
    leftTableView.dataSource = self;
    leftTableView.backgroundColor = RGBA(237, 238, 241, 1);
    leftTableView.separatorStyle = NO;
    leftTableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:leftTableView];
    
    
    x += width;
    width = ScreenWidth / 4.0;
    middleTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height - 64) style:UITableViewStylePlain];
    middleTableView.delegate = self;
    middleTableView.dataSource = self;
    middleTableView.separatorStyle = NO;
    middleTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:middleTableView];
    
    
    x += width;
    width = ScreenWidth * 3 / 8.0;
    rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height - 64) style:UITableViewStylePlain];
    rightTableView.delegate = self;
    rightTableView.dataSource = self;
    rightTableView.tableFooterView = [[UIView alloc]init];
    rightTableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:rightTableView];
    
    x = middleTableView.frame.size.width + middleTableView.frame.origin.x;
    y = middleTableView.frame.origin.y;
    width = 1;
    height = middleTableView.frame.size.height;
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    lineView.backgroundColor = RGBA(255, 255, 255, 0.6);
    [self.view addSubview:lineView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == leftTableView) {
        return bulidingArray.count;
    }
    else if(tableView == middleTableView)
    {
        return floorArray.count;
    }
    else
    {
        return roomArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    GuestCommunityChangeCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[GuestCommunityChangeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    if (tableView == leftTableView) {
        if (bulidingArray.count > indexPath.row) {
            cell.cellName = ((BulidingModel *)bulidingArray[indexPath.row]).buildingName;
            cell.backgroundColor =  RGBA(237, 238, 241, 1);
            if ([bulidingid isEqualToString:((BulidingModel *)bulidingArray[indexPath.row]).buildingId]) {
                cell.backgroundColor = [UIColor whiteColor];

            }
            else
            {
                cell.selectOrNot = NO;
            }

            
        }
        
    }
    else if(tableView == middleTableView)
    {
        if (floorArray.count > indexPath.row) {
            cell.cellName =((FloorsModel *)floorArray[indexPath.row]).floorName;
            if ([floorid isEqualToString:((FloorsModel *)floorArray[indexPath.row]).floorId]){
                cell.selectOrNot = YES;
                
            }
            else
            {
                cell.selectOrNot = NO;
            }
        }
    }
    else
    {
        if (roomArray.count > indexPath.row) {
           cell.cellName = ((RoomsModel *)roomArray[indexPath.row]).roomName;
            if ([roomid isEqualToString:((RoomsModel *)roomArray[indexPath.row]).roomId ]){
                cell.selectOrNot = YES;
            }
            else
            {
                cell.selectOrNot = NO;
            }
        }
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == leftTableView) {
        if([self IsHaveNetwork] == YES)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        }
        else
        {
        if (indexPath.row == 0) {
            [floorArray removeAllObjects];
            [roomArray removeAllObjects];
            [middleTableView reloadData];
            [rightTableView reloadData];
            [leftTableView reloadData];
            if (_HouseInfo) {
                self.HouseInfo(communityid,@"",@"",@"");
                [self BackClick];
            }
            return;
        }
//          bulidingid = [bulidingArray[indexPath.row]objectForKey:@"buildingid"];
        bulidingid =((BulidingModel *)bulidingArray[indexPath.row]).buildingId;
            [self RefreshHouseData:(int)indexPath.row selectFlag:0];
        [leftTableView reloadData];
        }
    }
    else if(tableView == middleTableView)
    {
        if([self IsHaveNetwork] == YES)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        }
        else
        {
        if (indexPath.row == 0) {
            [roomArray removeAllObjects];
            [rightTableView reloadData];
            [middleTableView reloadData];
            if (_HouseInfo) {
                self.HouseInfo(communityid,bulidingid,@"",@"");
                [self BackClick];
            }
            return;
        }
        
        floorid=((FloorsModel *)floorArray[indexPath.row]).floorId;
            [self RefreshHouseData:(int)indexPath.row selectFlag:1];
        [middleTableView reloadData];
        }
       
    }
    else if(tableView == rightTableView)
    {
        if([self IsHaveNetwork] == YES)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
            [self BackClick];
        }
        else
        {
        [rightTableView reloadData];
        if (indexPath.row == 0) {
            if (_HouseInfo) {
                self.HouseInfo(communityid,bulidingid,floorid,@"");
                [self BackClick];
            }
            return;
        }
        
         roomid = ((RoomsModel *)roomArray[indexPath.row]).roomId ;
        if (_HouseInfo) {
            self.HouseInfo(communityid,bulidingid,floorid,roomid);
            [self BackClick];
           
        }
        [rightTableView reloadData];
        }
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark  根据传进来的下标来更新楼栋，楼层，房间
/*
 index 下标
 flag 0表示楼栋改变了，1表示楼层改变了
 */
-(void)RefreshHouseData:(int )index selectFlag:(BOOL)flag
{
    if (flag) {
        
        RoomInfoLogic *roomLogic = [[RoomInfoLogic alloc]init];
         [roomLogic queryRoomInfo:floorid block:^(NSMutableArray *myRoomArray)
         {
             roomArray = myRoomArray;
         }
         ];
        
        if (roomArray.count > 0) {
            if (![((RoomsModel *)roomArray[0]).roomName isEqualToString:NSLocalizedString(@"allRoom", nil)]) {
                [roomArray insertObject:allRoom atIndex:0];
            }
        }
        [rightTableView reloadData];
        
    }
    else
    {
        [leftTableView reloadData];
        FloorsInfoLogic *floorLogic = [[FloorsInfoLogic alloc]init];
        [floorLogic queryFloorsInfo:bulidingid block:^(NSMutableArray *arr)
        {
            floorArray = arr;
        }
         ];
        
        if (floorArray.count > 0)
        {
            floorid = ((FloorsModel *)floorArray[0]).floorId;
            if (![((FloorsModel *)floorArray[0]).floorName isEqualToString:NSLocalizedString(@"allFloor", nil)]) {
                 [floorArray insertObject:allFloor atIndex:0];
            }
        }
        else
        {
            roomArray = nil;
            [middleTableView reloadData];
            [rightTableView reloadData];
        }
        [middleTableView reloadData];
        
        RoomInfoLogic *roomLogic = [[RoomInfoLogic alloc]init];
        [roomLogic queryRoomInfo:floorid block:^(NSMutableArray *myRoomArray)
        {
            roomArray =myRoomArray;
        }
         ];
        if (roomArray.count) {
            roomid = ((RoomsModel *)roomArray[0]).roomId;
            if (roomArray.count > 0) {
                if (![((RoomsModel *)roomArray[0]).roomName isEqualToString:NSLocalizedString(@"allRoom", nil)]) {
                    [roomArray insertObject:allRoom atIndex:0];
                }
            }
            [rightTableView reloadData];
        }
    }
}

-(void)clickBack
{
    if (_HouseInfo) {
        self.HouseInfo(communityid,@"",@"",@"");
    }
    [self BackClick];
}

-(void)BackClick
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)deleteRooms
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase deleteBulidingWithCommunityId:communityid];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase deleteFloorsInfoWithCommunityId:communityid];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    [roomDataBase deleteRoomWithCommunityId:communityid];
//    bulidingid = @"";
//    floorid = @"";
}


-(void)insertDataIntoRooms:(NSArray *)allBuildingInfo
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    for (NSDictionary * bDict in allBuildingInfo)
    {
        BulidingModel * bModel = [[BulidingModel alloc]init];
        bModel.buildingName = [bDict objectForKey:@"buildingname"];
        bModel.buildingId = [bDict objectForKey:@"buildingid"];
        bModel.buildingNo = [bDict objectForKey:@"buildingno"];
        [bulidingDataBase insertBulidingInfo:bModel withCommunityId:communityid];
        bModel.floors = [bDict objectForKey:@"floors"];
        for (NSDictionary * fDict in bModel.floors) {
            FloorsModel * fModel = [[FloorsModel alloc]init];
            fModel.floorId = [fDict objectForKey:@"floorid"];
            fModel.floorName = [fDict objectForKey:@"floorname"];
            fModel.floorNo  = [fDict objectForKey:@"floorno"];
            [floorDataBase insertFloorInfo:fModel withCommunityId:communityid buildingId:bModel.buildingId];
            fModel.rooms = [fDict objectForKey:@"rooms"];
            for (NSDictionary * rDict in fModel.rooms) {
                RoomsModel * rModel = [[RoomsModel alloc]init];
                rModel.roomId = [rDict objectForKey:@"roomid"];
                rModel.roomName = [rDict objectForKey:@"roomname"];
                rModel.roomNo = [rDict objectForKey:@"roomno"];
                rModel.isSelect = [rDict objectForKey:@"isSelected"];
                rModel.lockNo = [rDict objectForKey:@"lockno"];
                rModel.occupation = [rDict objectForKey:@"occupation"];
                [roomDataBase insertRoomInfo:rModel withFloorId:fModel.floorId withCommunityId:communityid];
            }
        }
    }
    
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.navigationController.view.frame.size.width / 2.0 -15, self.navigationController.view.frame.size.height / 2.0 - 15, 30, 30);
    _activityIndicator.hidden = YES;
    [self.navigationController.view addSubview:_activityIndicator];
}

@end
